<template>
	<div>
		<p><h3>批次信息</h3></p>
		<el-divider ></el-divider>
		<div id="batchInfoDiv">
      <el-table
      :data="batchInfo"
      :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center',fontSize:'15px'}"
      :cell-style="{'text-align':'center'}"
      style="width: 100%">
          <el-table-column
            :label="batchName"
            >
            <el-table-column
            prop="levelName"
            label="批次等级">
            </el-table-column>
            <el-table-column
            prop="phaseExpertStart"
            label="批次专家评审开始日期">
            </el-table-column>
            <el-table-column
            prop="phaseExpertEnd"
            label="批次专家评审结束日期">
            </el-table-column>
          </el-table-column>
      </el-table>
		</div>
    <div id="ProjectInfo">
        <el-dialog
          @close="dialogClose()"
          title="专家成绩评定"
          :visible.sync="AuditDialogVisible"
          width="50%"
          center>
          专家评分:
          <el-input v-model="expertAudit.score" style="width: 40%;"  placeholder="请输入0-100的分数"></el-input>
          <div style="margin-top: 15px;">
            <el-row type="flex" align="middle">
              <el-col :span="3">
                <p>打分表上传:</p>
              </el-col>
              <el-col :span="17">
                <el-upload
                  class="upload-demo"
                  :action='BaseApi+"/file/fileUpload"'
                  :headers="headerObj"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="UploadSuccess"
                  :before-remove="beforeRemove"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :show-file-list="false"
                  >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <span slot="tip" style="margin-left: 30px;font-size: 15px;font-weight: bold;color: #13CE66;"
                  class="el-upload__tip"
                  v-if="expertAudit.scorePath!='' && expertAudit.scorePath!=null"
                   >已上传</span>
                  <span slot="tip" style="margin-left: 30px;font-size: 15px;font-weight: bold;color: #ff0000;"
                  class="el-upload__tip"
                  v-else
                  >未上传</span>
                </el-upload>
              </el-col>
            </el-row>

          <div style="margin-top: 20px;">
          	<quill-editor v-model="expertAudit.message"> </quill-editor>
          </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogClose()">取 消</el-button>
            <el-button type="primary" @click="dialogSubmit()">确 定</el-button>
          </span>
        </el-dialog>
        <p><h3>项目信息</h3></p>
        <el-divider ></el-divider>
          <el-button type="primary" @click="downloadMaterial(scorePath,scorePathName)">打分表模板下载</el-button>
        <el-button type="success" @click="auditSubmit">审核提交</el-button>
        <div id="ProjectTable" style="margin-top: 25px;">
          <el-table
              :stripe='true'
              ref="multipleTable"
              :data="tableData"
              tooltip-effect="dark"
              style="width: 100%"
              @selection-change="handleSelectionChange"
              :header-cell-style="{'text-align':'center',background:'#eef1f6',color:'#606266',}"
              :cell-style="{'text-align':'center'}"
              >
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column
                label="项目名称"
                >
                <template slot-scope="scope">{{ scope.row.proName }}</template>
              </el-table-column>
              <el-table-column
                prop="classification"
                label="科目"
                >
              </el-table-column>
              <el-table-column
                prop="memberName"
                label="主持人"
               >
              </el-table-column>
              <el-table-column
                prop="proDepartment"
                label="所属学院"
               >
              </el-table-column>
              <el-table-column
                prop="message"
                label="审核状态"
                :formatter="auditStateFormat"
                >
              </el-table-column>
              <el-table-column
                prop="score"
                sortable
                label="分数"
                :formatter="scoreFormat"
                >
              </el-table-column>
              <el-table-column
                prop="score"
                label="打分表上传"
                :formatter="scoreTableFormat"
                >
              </el-table-column>
              <el-table-column
                label="详情内容"
                width="120">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="viewDetails(scope.row,scope.$index)">查看详情</el-button>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="120">
                <template slot-scope="scope">
                    <el-button size="mini" type="success" @click="AuditDialogOpen(scope.row,scope.$index)">审核</el-button>
                </template>
              </el-table-column>
            </el-table>
        </div>

    </div>
	</div>

</template>

<script>
import axios from 'axios'
export default {
		data() {
			return {
        headerObj: {
          token: this.$store.state.token,
          tokenHead: this.$store.state.tokenHead,
          jsession_id: this.$store.state.jsession_id
        },
        BaseApi:process.env.Base_API,
        tempIndex:'',
        headerObj: {
        	token: this.$store.state.token,
        	tokenHead: this.$store.state.tokenHead,
        	jsession_id: this.$store.state.jsession_id
        },
        expertAudit:{
          scoreId:'',
          score:'',
          message:'',
          scorePath:'',
        },
        AuditDialogVisible:false,
        classfy:[],
        //临时index
        batchName:'',
				thisBatchId:'',
        dialogProjectInfo:{
          departmentScore:'',
          committeeDate:'',
          proCommittee:'',
          proApproval:'',
        },
				batchInfo:[],
        teacherInfo:'',
        tableData: [],
        multipleSelection: [],
        scorePath:'',
        scorePathName:''
			}
		},
    created() {
      this.thisBatchId=this.$route.query.batch_id;
      this.teacherInfo=this.$store.state.info
      this.getBatchInfo()
      this.getClassfyByGhAndBatchId()
    },
    mounted(){
    },
		methods: {
      downloadMaterial(url,fileSort){
       axios.get(this.BaseApi+'/file/fileDownload', {
           headers: {
             token: this.$store.state.token,
             tokenHead: this.$store.state.tokenHead,
             jsession_id: this.$store.state.jsession_id
             },
             responseType: 'blob',
           params: {
            fileName:'test',
            fileUrl:url
           }
       }) .then((res)=>{
         console.log(res)
           //获取最后一个.的位置
           var index= fileSort.lastIndexOf(".");
           //获取后缀
           var ext = fileSort.substr(index+1);
           console.log(ext)
           //rar是用不了，暂且统一使用.zip下载
           var blog = new Blob([res.data],{type:'application/x-zip-compressed'})
           var  url = window.URL.createObjectURL(blog)
           var  a   = document.createElement('a')
           a.setAttribute('download',fileSort)
           a.setAttribute('href',url)
           a.click()
       }) .catch(function (error) { console.log(error); });
      },
      dialogClose(){
        Object.keys(this.expertAudit).forEach(key => this.expertAudit[key] = '');
        this.AuditDialogVisible=false
      },
      dialogSubmit(){
        if(this.expertAudit.score==""){
          this.$message({
                type: 'warning',
                message: '专家评分不能为空!',
                duration: 1000,
                offset:screen.height/2-200,
                center:true,
              })
          return
        }
        if(this.expertAudit.scorePath==""){
          this.$message({
                type: 'warning',
                message: '请上传打分表!',
                duration: 1000,
                offset:screen.height/2-200,
                center:true,
              })
          return
        }
        if(this.expertAudit.message==""){
          this.$message({
                type: 'warning',
                message: '专家评价不能为空!',
                duration: 1000,
                offset:screen.height/2-200,
                center:true,
              })
          return
        }
        for(let i=0 ; i<this.tableData.length;i++){
          if(this.tableData[i].score==this.expertAudit.score){
            this.$message({
                  type: 'warning',
                  message: '专家评分不能重复!',
                  duration: 1000,
                  offset:screen.height/2-200,
                  center:true,
                })
            return
          }
        }
        if(this.expertAudit.scoreId=="" || this.expertAudit.scoreId==undefined){
          this.creatExpertScore()
        }else{
          this.updateExpertScore()
        }
        this.getProjectDataAxios()
        Object.keys(this.expertAudit).forEach(key => this.expertAudit[key] = '');
        console.log(this.expertAudit)
        this.AuditDialogVisible=false
      },
      creatExpertScore(){
        this.$api.expert.creatExpertScore({
          batchId:this.thisBatchId,
          expertId:this.teacherInfo.gh,
          message:this.expertAudit.message,
          proId:this.tableData[this.tempIndex].proId,
          score:this.expertAudit.score,
          scorePath:this.expertAudit.scorePath,
        }).then((response)=>{
          console.log(response)
          if(response.data.code==200){
            this.$message({
              type: 'success',
              message: '评审成功!',
              duration: 1000,
              offset:screen.height/2-200,
              center:true,
            })
            return false
          }else{
            this.$message({
              type: 'error',
              message: '评审失败!',
              duration: 1000,
              offset:screen.height/2-200,
              center:true,
            })
            return false
          }
        })
      },
      updateExpertScore(){
        this.$api.expert.updateExpertScore({
          scoreId:this.expertAudit.scoreId,
          batchId:this.thisBatchId,
          expertId:this.teacherInfo.gh,
          message:this.expertAudit.message,
          proId:this.tableData[this.tempIndex].proId,
          score:this.expertAudit.score,
          scorePath:this.expertAudit.scorePath,
        }).then((response)=>{
          console.log(response)
          if(response.data.code==200){
            this.$message({
              type: 'success',
              message: '评审成功!',
              duration: 1000,
              offset:screen.height/2-200,
              center:true,
            })
            return false
          }else{
            this.$message({
              type: 'error',
              message: '评审失败!',
              duration: 1000,
              offset:screen.height/2-200,
              center:true,
            })
            return false
          }
        })
      },
      AuditDialogOpen(row,index){
        this.tempIndex=index
        this.AuditDialogVisible=true
        this.expertAudit.scoreId=row.scoreId
        this.expertAudit.score=row.score
        this.expertAudit.message=row.message
        this.expertAudit.scorePath=row.scorePath
        console.log(row)
      },
      UploadSuccess(response){
        console.log(response)
        this.expertAudit.scorePath=response.data[0].filePath
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      //得到该专家所评审的项目标签，如理科，文科
      getClassfyByGhAndBatchId(){
        this.$api.expert.getExpertByBatchId({batchId:this.thisBatchId}).then((response)=>{
          response.data.data.forEach(item=>{
            if(item.gh==this.teacherInfo.gh && item.batchId==this.thisBatchId){
              this.classfy.push(item.classification)
            }
          })
          this.getProjectDataAxios()
        })
      },
      //得到此页面的审核状态message和Score
      getExpertScores(){
        this.$api.expert.getExpertScores().then((response)=>{
          console.log(response)
          for(let i=0;i<response.data.data.length;i++){
            for(let j=0;j<this.tableData.length;j++){
              if(response.data.data[i].proId==this.tableData[j].proId){
                this.$set(this.tableData[j],"scoreId",response.data.data[i].scoreId)
                this.$set(this.tableData[j],"scorePath",response.data.data[i].scorePath)
                this.$set(this.tableData[j],"score",response.data.data[i].score)
                this.$set(this.tableData[j],"message",this.getSimpleText(response.data.data[i].message))
              }
            }
          }
        })
      },
      //审核状态的格式填写，有值返回值，无值则返回未填写
      auditStateFormat(row,column){
          if(row.message==null || row.message==''){
            return '未填写'
          }else{
            return row.message
          }
      },
      scoreTableFormat(row,column){
          if(row.scorePath==null || row.scorePath=='' || row.scorePath==undefined){
            return '未填写'
          }else{
            return '已填写'
          }
      },
      //分数状态的格式填写，有值返回值，无值则返回未填写
      scoreFormat(row,column){
          if(row.score==null || row.score==''){
            return '未填写'
          }else{
            return row.score
          }
      },
      //审核提交
      auditSubmit(){
        for(let i=0;i<this.tableData.length;i++){
          if(this.tableData[i].score==undefined || this.tableData[i].message==undefined ){
            this.$message({
              type: 'error',
              message: '尚有项目未作出选择!',
              duration: 2000,
              offset:screen.height/2-200,
              center:true
            })
            return
          }
        }
        this.$store.commit('getTodoList')
        this.UpdateBatchInfo()
      },
      UpdateBatchInfo(){
        this.$api.batch.updateBatchStatus({
          batchId:this.thisBatchId,
          status:3,
        }).then((response)=>{
          this.goAuditBatch()
          console.log(response)
        })
      },
      //路由跳转
      goAuditBatch(){
        this.$router.push({path:'/expertApprovalAudit'})
      },
      //查看详情按钮路由跳转
      viewDetails(row,index){
        this.$router.push({path:'/expertProjectAuditPdf',query:{proId:row.proId,batchId:this.thisBatchId,allProject:JSON.stringify(this.tableData)}})
      },
      //yyyy-MM-dd时间格式
      getNowDate(){
        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1): nowDate.getMonth() + 1;
        var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
         .getDate();
        var dateStr = year + "-" + month + "-" + day;
        return  dateStr
      },
      //去除富文本格式方法
      getSimpleText(html){
        var re1 = new RegExp("<.+?>","g");//匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
        var msg = html.replace(re1,'');//执行替换成空字符
        return msg;
      },
      //yyyy-MM-dd hh：mm：ss时间格式
      getNowFormatDate() {
          var date = new Date();
          var seperator1 = "-";
          var seperator2 = ":";
          var month = date.getMonth() + 1;
          var strDate = date.getDate();
          if (month >= 1 && month <= 9) {
              month = "0" + month;
          }
          if (strDate >= 0 && strDate <= 9) {
              strDate = "0" + strDate;
          }
          var Hours= date.getHours()
          if (Hours >= 0 && Hours <= 9) {
              Hours = "0" + Hours;
          }

          var Minutes= date.getMinutes()
          if (Minutes >= 0 && Minutes <= 9) {
              Minutes = "0" + Minutes;
          }

          var Seconds= date.getSeconds()
          if (Seconds >= 0 && Seconds <= 9) {
              Seconds = "0" + Seconds;
          }
          var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                  + " " + Hours + seperator2 + Minutes
                  + seperator2 + Seconds;
          return currentdate;
      },
      //得到该批次的信息
			getBatchInfo(){
				this.$api.batch.getAllBatch()
				.then((response)=>{
					console.log(response.data.data)
					this.batchInfo.push(response.data.data.find(item=>item.batchId==this.thisBatchId))
          console.log(this.batchInfo)
          this.batchName=this.batchInfo[0].batchName
          this.scorePath=this.batchInfo[0].scorePath
          this.scorePathName=this.batchInfo[0].scorePathName
				})
			},
      //得到所有项目并组合项目对象
        getProjectDataAxios() {
          let that = this;
          this.$api.batch.getProjectByBatchId({
        	batchId: this.thisBatchId
          }).then(
            (response)=>{
        	  console.log(response)
              var tempData=response.data.data
              var result=[],Temp=[]
              var isfl
              for(var i = 0 ;i < tempData.length;i++ ){
                isfl=false;
                for(var j=0;j< result.length;j++){
                  if(tempData[i].proId == result[j].proId){
                    isfl=true
                    break}}
                if(!isfl){
                  result.push(tempData[i])
                }}
                console.log(result)
                for(let i = 0;i<result.length;i++){
                  for(let j=0;j<this.classfy.length;j++){
                    if(result[i].classification==this.classfy[j]){
                      Temp.push(result[i])
                    }
                  }
                }
                this.tableData=Temp.filter((item)=>{ return item.ranking==1 && item.proApproval==4 || item.ranking==1 && item.proApproval==3
              })
              this.getExpertScores()
        	})
        },
       toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      }
		},
	}

</script>

<style scoped>
	#batchInfoDivContent{
		margin: 20px;
	}
	#batchInfoDivContent div{
		margin-top: 20px;
	}
	div > p,h4{
		display: inline;
	}


</style>
